package com.qut.graduate.busrtquery.fragment;

import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qut.graduate.busrtquery.BRTQCache;
import com.qut.graduate.busrtquery.BRTQConstant;
import com.qut.graduate.busrtquery.R;
import com.qut.graduate.busrtquery.adapter.BusLineAdapter;
import com.qut.graduate.busrtquery.adapter.LineQueryAdapter;
import com.qut.graduate.busrtquery.bean.BusInfoLineQuery;
import com.qut.graduate.busrtquery.bean.Route;
import com.qut.graduate.busrtquery.bean.User;
import com.qut.graduate.busrtquery.greendao.bean.BusLine;
import com.qut.graduate.busrtquery.greendao.bean.BusLineCollect;
import com.qut.graduate.busrtquery.greendao.controller.DBController;
import com.qut.graduate.busrtquery.interfaces.OnItemClickListener;
import com.qut.graduate.busrtquery.ui.MainActivity;
import com.qut.graduate.busrtquery.utils.common.FormatUtils;
import com.qut.graduate.busrtquery.utils.common.LogUtils;
import com.qut.graduate.busrtquery.utils.net.HttpUtil;
import com.qut.graduate.busrtquery.utils.uiabout.ToastColorfulUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import cn.bmob.v3.BmobUser;

/**
 * @Author WLL
 * @Time: 2019/3/23 16:39
 */
public class LineQueryFragment extends BaseFragment {
    private static final String TAG = "LineQueryFragment";
    private Context mContext;
    private List<BusInfoLineQuery> mBusInfoLineQueryList = new ArrayList<>();
    private List<BusLine> mHistoryBusLineList = new ArrayList<>();
    private List<BusLineCollect> mCollectBusLineList = new ArrayList<>();
    private LineQueryAdapter lineQueryAdapter;
    private BusLineAdapter mHistoryBusLineAdapter;
    private BusLineAdapter mCollectBusLineAdapter;

    private LinearLayout mTopLayout;
    private LinearLayout mHistoryCollectionTopLayout;
    private LinearLayout mHistoryCollectionLayout;
    private EditText mSearchEditText;
    private Button mHistoryBtn;
    private Button mCollectionBtn;
    private Button mHistoryClearBtn;
    private LinearLayout mHistoryLayout;
    private TextView mCollectText;
    private LinearLayout mCollectLayout;
    private RecyclerView mHistoryRecyclerView;
    private RecyclerView mCollectionRecyclerView;
    private RecyclerView mBusRouteRecyclerView;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_line_query;
    }

    protected void init() {
        mContext = getActivity();
        initView();
        initEvent();
    }

    private void initView() {
        mTopLayout = mRootView.findViewById(R.id.line_query_top_layout);
        mHistoryCollectionTopLayout = mRootView.findViewById(R.id.line_query_history_collection_top_layout);
        mHistoryCollectionLayout = mRootView.findViewById(R.id.line_query_history_collection_layout);
        mSearchEditText = mRootView.findViewById(R.id.line_query_search_editText);
        mHistoryBtn = mRootView.findViewById(R.id.line_query_history_btn);
        mCollectionBtn = mRootView.findViewById(R.id.line_query_collection_btn);
        mHistoryClearBtn = mRootView.findViewById(R.id.line_query_history_clear_btn);
        mCollectText = mRootView.findViewById(R.id.line_query_collection_textView);
        mCollectLayout = mRootView.findViewById(R.id.line_query_collection_layout);
        mHistoryLayout = mRootView.findViewById(R.id.line_query_history_layout);
        mHistoryRecyclerView = mRootView.findViewById(R.id.line_query_history_recyclerView);
        mCollectionRecyclerView = mRootView.findViewById(R.id.line_query_collection_recyclerView);
        mBusRouteRecyclerView = mRootView.findViewById(R.id.line_query_bus_route_recyclerView);

        mHistoryBtn.setOnClickListener(this);
        mCollectionBtn.setOnClickListener(this);
        mHistoryClearBtn.setOnClickListener(this);
    }

    private void initEvent() {
        mHistoryBusLineList.addAll(BRTQCache.getInstance().getBusLineHistoryList());
        mHistoryRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mHistoryBusLineAdapter = new BusLineAdapter(mContext, mHistoryBusLineList, 0);
        mHistoryBusLineAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                Map<String, Route> mApiRoutesMap = BRTQCache.getInstance().getmApiRoutesMap();
                if (mApiRoutesMap != null && mApiRoutesMap.containsKey(mHistoryBusLineList.get(position).getName())) {
                    BRTQCache.getInstance().setBusLine(mHistoryBusLineList.get(position));
                    Route route = mApiRoutesMap.get(mHistoryBusLineList.get(position).getName());
                    String url = BRTQConstant.URL_BUS_LINE_INFO.concat(route.getRouteid());
                    LogUtils.d("----LineQueryFragment  url:" + url, getClass());
                    HttpUtil.getInstance().getAsyn(url, (MainActivity) getActivity(), BRTQConstant.HTTP_TAG_BUS_LINE_INFO_HC);
                    mHistoryBusLineList.get(position).setTime(BRTQConstant.timeFormat.format(System.currentTimeMillis()));
                    updateAllBusLineData(mHistoryBusLineList.get(position));
                }
            }
        });
        mHistoryRecyclerView.setAdapter(mHistoryBusLineAdapter);

        mCollectBusLineList.addAll(BRTQCache.getInstance().getBusLineCollectList());
        LogUtils.d("----LineQueryFragment  mCollectBusLineList:" + mCollectBusLineList, getClass());
        mCollectionRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mCollectBusLineAdapter = new BusLineAdapter(mContext, mCollectBusLineList, 1);
        mCollectBusLineAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                Map<String, Route> mApiRoutesMap = BRTQCache.getInstance().getmApiRoutesMap();
                if (mApiRoutesMap != null && mApiRoutesMap.containsKey(mCollectBusLineList.get(position).getName())) {
                    BusLine busLine = new BusLine(mCollectBusLineList.get(position));
                    BRTQCache.getInstance().setBusLine(busLine);
                    Route route = mApiRoutesMap.get(mCollectBusLineList.get(position).getName());
                    String url = BRTQConstant.URL_BUS_LINE_INFO.concat(route.getRouteid());
                    LogUtils.d("----LineQueryFragment  url:" + url, getClass());
                    HttpUtil.getInstance().getAsyn(url, (MainActivity) getActivity(), BRTQConstant.HTTP_TAG_BUS_LINE_INFO_HC);
                }
            }
        });
        mCollectionRecyclerView.setAdapter(mCollectBusLineAdapter);
        setHistoryClearBtnVisibility();
        mSearchEditText.addTextChangedListener(new MyTextWatcher());
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        updateCollectBusLineRecyView();
        if (hidden) {
            changeBusRouteOrHisCollect(false);
            changeHistoryCollection(true);
            mSearchEditText.setText("");
        } else {
            updateHistoryBusLineRecyView();
            if (getActivity() != null) {
                mTopLayout.setBackgroundColor(((MainActivity) getActivity()).getPrimaryColor());
                mHistoryCollectionTopLayout.setBackgroundColor(((MainActivity) getActivity()).getPrimaryColor());
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.line_query_history_btn:
                changeHistoryCollection(true);
                break;
            case R.id.line_query_collection_btn:
                changeHistoryCollection(false);
                break;
            case R.id.line_query_history_clear_btn:
                BRTQCache.getInstance().getBusLineHistoryList().clear();
                updateHistoryBusLineRecyView();
                DBController.getInstance().deleteAllTable(BRTQConstant.DB_TABLE_TYPE_BUS_LINE_HISTORY);
                break;
        }
    }

    /**
     * 监听线路搜索顶部的searchEditText的内容改变
     */
    private class MyTextWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            String searchLine = mSearchEditText.getText().toString().trim();
            if (FormatUtils.isNumber(searchLine)) {
                changeBusRouteOrHisCollect(true);
                String url = BRTQConstant.URL_LINE_QUERY.concat(searchLine);
                HttpUtil.getInstance().getAsyn(url, (MainActivity) getActivity(), BRTQConstant.HTTP_TAG_LINE_QUERY);
            } else {
                if (!((MainActivity) getActivity()).getmFragmentList().get(BRTQConstant.FRAGMENT_LINE_QUERY).isHidden()
                        && !searchLine.equals(""))
                    ToastColorfulUtils.info("您输入的内容不是纯数字");
                changeBusRouteOrHisCollect(false);
            }
        }
    }

    /**
     * 主页查询到公交线路后显示到线路查询对应的mBusRouteRecyclerView中
     *
     * @param busInfoLineQueryList
     */
    public void setBusRouteRecyclerViewData(final List<BusInfoLineQuery> busInfoLineQueryList) {
        if (busInfoLineQueryList != null && busInfoLineQueryList.size() > 0) {
            if (getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mBusInfoLineQueryList.clear();
                        mBusInfoLineQueryList.addAll(busInfoLineQueryList);
                        mBusRouteRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
                        lineQueryAdapter = new LineQueryAdapter(mContext, mBusInfoLineQueryList);
                        lineQueryAdapter.setOnItemClickListener(new OnItemClickListener() {
                            @Override
                            public void onClick(View view, int position) {
                                Map<String, Route> mApiRoutesMap = BRTQCache.getInstance().getmApiRoutesMap();
                                if (mApiRoutesMap != null && mApiRoutesMap.containsKey(mBusInfoLineQueryList.get(position).getName())) {
                                    BRTQCache.getInstance().setBusInfoLineQuery(mBusInfoLineQueryList.get(position));
                                    Route route = mApiRoutesMap.get(mBusInfoLineQueryList.get(position).getName());
                                    String url = BRTQConstant.URL_BUS_LINE_INFO.concat(route.getRouteid());
                                    LogUtils.d("----LineQueryFragment  url:" + url, getClass());
                                    HttpUtil.getInstance().getAsyn(url, (MainActivity) getActivity(), BRTQConstant.HTTP_TAG_BUS_LINE_INFO);
                                    BusLine busLine = new BusLine(mBusInfoLineQueryList.get(position));
                                    updateAllBusLineData(busLine);
                                } else {
                                    ToastColorfulUtils.info("未查到该线路的公交实时信息");
                                }
                            }
                        });
                        mBusRouteRecyclerView.setAdapter(lineQueryAdapter);
                    }
                });
            }
        } else {
            if (getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mBusInfoLineQueryList.clear();
                        lineQueryAdapter.notifyDataSetChanged();
                        ToastColorfulUtils.info("您查询的线路不存在，请重新输入");
                    }
                });
            }
        }
    }

    /**
     * 点击  查询后的某条线路 或 线路查询历史中的某条线路  更新展示的线路历史的recyclerview、内存及数据库中的数据
     */
    public void updateAllBusLineData(BusLine newBusLine) {
        if (BRTQCache.getInstance().getBusLineHistoryList() != null) {
            if (BRTQCache.getInstance().getBusLineHistoryList().size() > 0) {
                for (int i = 0; i < BRTQCache.getInstance().getBusLineHistoryList().size(); i++) {
                    if (BRTQCache.getInstance().getBusLineHistoryList().get(i).getName().equals(newBusLine.getName())) {
                        BRTQCache.getInstance().getBusLineHistoryList().get(i).setTime(newBusLine.getTime());
                        insertOrUpdateBusLineHistoryTable(BRTQConstant.DB_BUS_LINE_HISTORY_UPDATE,
                                BRTQCache.getInstance().getBusLineHistoryList().get(i));
                        break;
                    } else { // 线路名字不一样，即还没查询过该线路
                        if (i == BRTQCache.getInstance().getBusLineHistoryList().size() - 1) {
                            BRTQCache.getInstance().getBusLineHistoryList().add(newBusLine);
                            insertOrUpdateBusLineHistoryTable(BRTQConstant.DB_BUS_LINE_HISTORY_INSERT,newBusLine);
                        }
                    }
                }
            }
            if (BRTQCache.getInstance().getBusLineHistoryList().size() == 0) {
                BRTQCache.getInstance().getBusLineHistoryList().add(newBusLine);
                insertOrUpdateBusLineHistoryTable(BRTQConstant.DB_BUS_LINE_HISTORY_INSERT,newBusLine);
            }
            updateHistoryBusLineRecyView();
        }
    }

    /**
     * 更新查询历史RecyclerView
     */
    public void updateHistoryBusLineRecyView() {
        mHistoryBusLineList.clear();
        mHistoryBusLineList.addAll(BRTQCache.getInstance().getBusLineHistoryList());
        sortBusLineHistory();
        mHistoryBusLineAdapter.notifyDataSetChanged();
        setHistoryClearBtnVisibility();
    }

    /**
     * 更新收藏线路RecyclerView
     */
    public void updateCollectBusLineRecyView() {
        User user = BmobUser.getCurrentUser(User.class);
        if (user != null) {
            if (mCollectionRecyclerView != null)
                mCollectionRecyclerView.setVisibility(View.VISIBLE);
            if (mCollectText != null)
                mCollectText.setVisibility(View.GONE);
            mCollectBusLineList.clear();
            mCollectBusLineList.addAll(BRTQCache.getInstance().getBusLineCollectList());
            sortBusLineCollect();
            mCollectBusLineAdapter.notifyDataSetChanged();
        } else {
            if (mCollectionRecyclerView != null)
                mCollectionRecyclerView.setVisibility(View.GONE);
            if (mCollectText != null)
                mCollectText.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 将展示的线路历史按照时间进行排序
     */
    public void sortBusLineHistory() {
        Collections.sort(mHistoryBusLineList, new Comparator<BusLine>() {
            public int compare(BusLine o1, BusLine o2) {
                return o2.getTime().compareTo(o1.getTime());
            }
        });
    }

    /**
     * 将展示的收藏线路按照时间进行排序
     */
    public void sortBusLineCollect() {
        Collections.sort(mCollectBusLineList, new Comparator<BusLineCollect>() {
            public int compare(BusLineCollect o1, BusLineCollect o2) {
                return o2.getTime().compareTo(o1.getTime());
            }
        });
    }

    /**
     * 显示或隐藏 “清除查询历史” 按钮
     */
    public void setHistoryClearBtnVisibility() {
        if (mHistoryBusLineList.size() > 0) mHistoryClearBtn.setVisibility(View.VISIBLE);
        else mHistoryClearBtn.setVisibility(View.GONE);
    }

    /**
     * 将查询历史插入到数据库的表中
     */
    public void insertOrUpdateBusLineHistoryTable(int type, BusLine busLine) {
        if (type == BRTQConstant.DB_BUS_LINE_HISTORY_UPDATE)
            DBController.getInstance().updateTable(BRTQConstant.DB_TABLE_TYPE_BUS_LINE_HISTORY, busLine);
        if (type == BRTQConstant.DB_BUS_LINE_HISTORY_INSERT)
            DBController.getInstance().insertTable(BRTQConstant.DB_TABLE_TYPE_BUS_LINE_HISTORY, busLine);
    }

    /**
     * 切换线路历史、线路收藏的recyclerView,
     *
     * @param isHistoryOrCollection true显示历史, false显示线路收藏
     */
    public void changeHistoryCollection(boolean isHistoryOrCollection) {
        if (isHistoryOrCollection) {
            mHistoryBtn.setBackgroundResource(R.drawable.shape_btn_corners_5dp);
            mCollectionBtn.setBackgroundColor(Color.TRANSPARENT);
            mHistoryLayout.setVisibility(View.VISIBLE);
            mCollectLayout.setVisibility(View.GONE);
        } else {
            mHistoryBtn.setBackgroundColor(Color.TRANSPARENT);
            mCollectionBtn.setBackgroundResource(R.drawable.shape_btn_corners_5dp);
            mHistoryLayout.setVisibility(View.GONE);
            mCollectLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 切换显示查询到的公交线路、线路历史及收藏界面
     *
     * @param isBusRouteOrHisCollect true显示公交线路, false显示线路历史及收藏界面
     */
    public void changeBusRouteOrHisCollect(boolean isBusRouteOrHisCollect) {
        if (isBusRouteOrHisCollect) {
            mBusRouteRecyclerView.setVisibility(View.VISIBLE);
            mHistoryCollectionLayout.setVisibility(View.GONE);
        } else {
            mBusInfoLineQueryList.clear();
            lineQueryAdapter = new LineQueryAdapter(mContext, mBusInfoLineQueryList);
            lineQueryAdapter.notifyDataSetChanged();
            if (mBusRouteRecyclerView != null)
                mBusRouteRecyclerView.setVisibility(View.GONE);
            if (mHistoryCollectionLayout != null)
                mHistoryCollectionLayout.setVisibility(View.VISIBLE);
        }
    }

}